package com.ruogu.codegeneration.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.ruogu.codegeneration.exception.BusinessException;
import com.ruogu.codegeneration.exception.ErrorCode;
import com.ruogu.codegeneration.mapper.UserMapper;
import com.ruogu.codegeneration.model.dto.user.UserQueryRequest;
import com.ruogu.codegeneration.model.entity.User;
import com.ruogu.codegeneration.model.enums.UserRoleEnum;
import com.ruogu.codegeneration.model.vo.user.LoginUserVO;
import com.ruogu.codegeneration.model.vo.user.UserVO;
import com.ruogu.codegeneration.service.UserService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import static com.ruogu.codegeneration.constant.UserConstant.USER_LOGIN_STATE;
import static com.ruogu.codegeneration.utils.PasswordUtil.getEncryptPassword;

/**
 * 服务层实现。
 *
 * @author ruogu
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    /**
     * 默认用户名
     */
    private static final String DEFAULT_USER_NAME = "匿名用户";

    /**
     * 用户注册
     *
     * @param userAccount   用户账户
     * @param userPassword  用户密码
     * @param checkPassword 校验密码
     * @return 新用户 id
     */
    @Override
    public long userRegister(String userAccount, String userPassword, String checkPassword) {
        // 1. 校验
        validateRegisterParams(userAccount, userPassword, checkPassword);

        // 2. 检查是否重复
        QueryWrapper queryWrapper = QueryWrapper.create();
        queryWrapper
                .where(User::getUserAccount)
                .eq(userAccount);
        System.out.println("sql-> " + queryWrapper.toSQL());
        if (this.mapper.selectCountByQuery(queryWrapper) > 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号已被注册");
        }

        // 3. 加密
        String encryptPassword = getEncryptPassword(userPassword);

        // 4. 插入数据
        User user = new User();
        user.setUserAccount(userAccount);
        user.setUserPassword(encryptPassword);
        user.setUserName(DEFAULT_USER_NAME);
        user.setUserRole(UserRoleEnum.USER.getValue());

        boolean saveResult = this.save(user);
        if (!saveResult) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "注册失败，数据库错误");
        }

        return user.getId();
    }

    /**
     * 用户登录
     *
     * @param userAccount  用户账户
     * @param userPassword 用户密码
     * @param request      请求
     * @return 脱敏后的用户信息
     */
    @Override
    public LoginUserVO userLogin(String userAccount, String userPassword, HttpServletRequest request) {
        // 1. 校验
        if (StrUtil.hasBlank(userAccount, userPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        if (userAccount.length() < 4) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号错误");
        }
        if (userPassword.length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "密码错误");
        }

        // 2. 加密
        String encryptPassword = getEncryptPassword(userPassword);

        // 3. 查询用户是否存在
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.where(User::getUserAccount).eq(userAccount);
        queryWrapper.where(User::getUserPassword).eq(encryptPassword);

        User user;
        try {
            user = this.mapper.selectOneByQuery(queryWrapper);
        } catch (Exception e) {
            log.error("数据库查询异常", e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "系统错误");
        }

        // 用户不存在或密码错误
        if (user == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户不存在或密码错误");
        }

        // 4. 安全增强：防止 Session 固定攻击
        HttpSession session = request.getSession(false);
        if (session != null) {
            session.invalidate();
        }
        request.getSession(true).setAttribute(USER_LOGIN_STATE, user);

        // 5. 获得脱敏后的用户信息
        return this.getLoginUserVO(user);
    }


    /**
     * 获取脱敏的已登录用户信息
     *
     * @param user 已登录用户完整信息
     * @return 用户登录返回信息
     */
    @Override
    public LoginUserVO getLoginUserVO(User user) {
        if (user == null) {
            return null;
        }
        LoginUserVO loginUserVO = new LoginUserVO();
        BeanUtil.copyProperties(user, loginUserVO);
        return loginUserVO;
    }

    /**
     * 获取当前登录用户
     *
     * @param request 请求
     * @return 当前登录用户
     */
    @Override
    public User getLoginUser(HttpServletRequest request) {
        Object userObj = verificationRequest(request);

        User currentUser = (User) userObj;

        // 检查用户ID是否为空
        if (currentUser.getId() == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR, "登录用户不存在");
        }

        // 从数据库查询用户信息（追求性能的话可以注释，直接返回上述结果）
        long userId = currentUser.getId();
        currentUser = this.getById(userId);
        if (currentUser == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR, "用户不存在");
        }

        return currentUser;
    }

    /**
     * 用户注销
     *
     * @param request 请求
     * @return 是否注销成功
     */
    @Override
    public boolean userLogout(HttpServletRequest request) {
        // 参数校验
        if (request == null) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "请求参数为空");
        }

        // 获取Session并判断是否已登录
        HttpSession session = request.getSession();
        Object userObj = session.getAttribute(USER_LOGIN_STATE);
        if (userObj == null) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "未登录");
        }

        // 移除登录态
        session.removeAttribute(USER_LOGIN_STATE);
        return true;
    }

    /**
     * 将User对象转换为UserVO对象
     *
     * @param user 用户实体对象，包含用户的所有信息
     * @return UserVO 用户返回对象，用于向前端展示用户信息
     */
    @Override
    public UserVO getUserVO(User user) {
        if (user == null) {
            return null;
        }
        UserVO userVO = new UserVO();
        BeanUtil.copyProperties(user, userVO);
        return userVO;
    }

    /**
     * 将用户实体列表转换为用户VO列表
     *
     * @param userList 用户实体列表
     * @return 用户VO列表
     */
    @Override
    public List<UserVO> getUserVOList(List<User> userList) {
        if (CollUtil.isEmpty(userList)) {
            return new ArrayList<>();
        }
        return userList.stream().map(this::getUserVO).collect(Collectors.toList());
    }

    /**
     * 获取查询条件 QueryWrapper
     *
     * @param userQueryRequest 用户查询请求
     * @return 查询条件
     */
    @Override
    public QueryWrapper getQueryWrapper(UserQueryRequest userQueryRequest) {
        if (userQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数为空");
        }
        Long id = userQueryRequest.getId();
        String userAccount = userQueryRequest.getUserAccount();
        String userName = userQueryRequest.getUserName();
        String userProfile = userQueryRequest.getUserProfile();
        String userRole = userQueryRequest.getUserRole();
        String sortField = userQueryRequest.getSortField();
        String sortOrder = userQueryRequest.getSortOrder();
        return QueryWrapper.create()
                .eq(User::getId, id)
                .eq(User::getUserRole, userRole)
                .like(User::getUserAccount, userAccount)
                .like(User::getUserName, userName)
                .like(User::getUserProfile, userProfile)
                .orderBy(sortField, "ascend".equals(sortOrder));
    }


    private static Object verificationRequest(HttpServletRequest request) {
        if (request == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR, "请求对象为空");
        }

        // 获取session并检查是否为空
        HttpSession session = request.getSession();
        if (session == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR, "会话不存在");
        }

        // 从session中获取用户对象
        Object userObj = session.getAttribute(USER_LOGIN_STATE);
        if (userObj == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR, "用户未登录");
        }

        // 类型检查
        if (!(userObj instanceof User)) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR, "用户信息格式错误");
        }
        return userObj;
    }


    private void validateRegisterParams(String userAccount, String userPassword, String checkPassword) {
        if (StrUtil.hasBlank(userAccount, userPassword, checkPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        if (userAccount.length() < 4) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户账号过短");
        }
        if (userPassword.length() < 8 || checkPassword.length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户密码过短");
        }
        if (!userPassword.equals(checkPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "两次输入的密码不一致");
        }
    }


}
